import 'package:dance_todo/db/bean_event.dart';
import 'package:dance_todo/db/bean_record.dart';
import 'package:dance_todo/main.dart';
import 'package:dance_todo/pages/controller_schedule.dart';
import 'package:dance_todo/pages/page_event.dart';
import 'package:dance_todo/res/res_colors.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:lottie/lottie.dart';

class SchedulePage extends StatefulWidget {
  const SchedulePage({Key? key}) : super(key: key);

  @override
  State<SchedulePage> createState() => _SchedulePageState();
}

class _SchedulePageState extends State<SchedulePage> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    ScheduleCtrl.to.queryRecordsForDay(DateTime.now());
    ScheduleCtrl.to.queryEvents();
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.black87,
      child: SafeArea(
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Container(
                child: const Text(
                  '今日任务',
                  style: TextStyle(
                    color: ColorTitle,
                    fontSize: 70.0,
                  ),
                ),
              ),
              Expanded(child: buildEventsContainer()),
              buildMenuRow(),
              SizedBox(height: 20.0),
            ],
          ),
        ),
      ),
    );
  }

  Widget buildEventsContainer() {
    return Obx(() {
      var records = ScheduleCtrl.to.records.value;
      var recordsTemp = [];
      recordsTemp.addAll(records);
      recordsTemp.add(Record());
      return Padding(
        padding: const EdgeInsets.all(10.0),
        child: GridView.builder(
          gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 2,
            mainAxisSpacing: 12,
            crossAxisSpacing: 20,
            childAspectRatio: 1 / 0.7,
          ),
          itemCount: recordsTemp.length,
          itemBuilder: (BuildContext context, int index) {
            var record = recordsTemp[index];
            if (record.isEmpty()) {
              return buildRecordAddItem();
            } else {
              return buildRecordItem(record: record);
            }
          },
        ),
      );
    });
  }

  Widget buildRecordItem({Record? record}) {
    return Obx(() {
      int selectEventId = ScheduleCtrl.to.selectRecordId.value;
      bool isSelect = record!.id == selectEventId;
      return GestureDetector(
        onTap: () {
          ScheduleCtrl.to.saveSelectRecordId(record.id);
          Get.back();
        },
        child: Container(
          decoration: BoxDecoration(
            color: isSelect
                ? Colors.pinkAccent.withAlpha(150)
                : Colors.grey.withAlpha(50),
          ),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Container(
                child: Text(
                  record.name!,
                  style: const TextStyle(
                    fontSize: 30.0,
                    color: ColorActiveRed,
                  ),
                ),
              ),
              SizedBox(height: 10),
              Container(
                child: RichText(
                  text: TextSpan(
                    text: '进度：',
                    style: TextStyle(
                      fontSize: 20.0,
                      color: ColorHint,
                      fontFamily: "MiSansBold",
                    ),
                    children: [
                      TextSpan(
                        text: "${record.doneCount}",
                        style: TextStyle(
                          fontSize: 20.0,
                          color: ColorActiveRed,
                        ),
                      ),
                      TextSpan(
                        text: "/",
                        style: TextStyle(
                          fontSize: 20.0,
                          color: ColorHint,
                        ),
                      ),
                      TextSpan(
                        text: "${record.totalCount}",
                        style: TextStyle(
                          fontSize: 20.0,
                          color: ColorTitle,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      );
    });
  }

  Widget buildMenuRow() {
    return Container(
      child: Row(
        children: [
          GestureDetector(
            onTap: () {
              Get.back();
            },
            child: Container(
              width: 120.0,
              height: 100.0,
              decoration: BoxDecoration(
                color: Colors.grey.withAlpha(50),
                borderRadius: const BorderRadius.only(
                  topRight: Radius.circular(100.0),
                  bottomRight: Radius.circular(100.0),
                ),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    '打卡',
                    style: TextStyle(
                      color: ColorActiveRed,
                      fontSize: 40.0,
                    ),
                  ),
                ],
              ),
            ),
          ),
          Expanded(child: Container()),
        ],
      ),
    );
  }

  ///创建
  void createEvent() {
    Get.to(() => const EventPage());
  }

  //notice 创建新增reocrd按钮
  Widget buildRecordAddItem() {
    return GestureDetector(
      onTap: () {
        var events = ScheduleCtrl.to.events.value;
        List<Event> tempEvents = [];
        tempEvents.add(Event());
        tempEvents.addAll(events);
        //step 过滤掉已经添加的记录
        tempEvents.removeWhere((event){
          for (var record in ScheduleCtrl.to.records) {
            if (record.name==event.name) {
              return true;
            }
          }
          return false;
        });
        Get.defaultDialog(
          backgroundColor: Colors.white,
          title: '-选择项目-',
          titleStyle: TextStyle(
            color: Colors.black87,
            fontSize: 30.0,
          ),
          content: Container(
            height: 400,
            child: Padding(
              padding: const EdgeInsets.all(20.0),
              child: SingleChildScrollView(
                child: Column(
                  children: tempEvents.map((e) {
                    if (e.isEmpty()) {
                      return buildEventAddItem();
                    } else {
                      return buildEventItem(e);
                    }
                  }).toList(),
                ),
              ),
            ),
          ),
        ).then((value){
          ScheduleCtrl.to.queryRecordsForDay(DateTime.now());
        });
      },
      child: Container(
        decoration: BoxDecoration(
          color: Colors.grey.withAlpha(50),
        ),
        alignment: Alignment.center,
        child: Text(
          '+',
          style: const TextStyle(
            fontSize: 60.0,
            color: Colors.white70,
          ),
        ),
      ),
    );
  }

  Widget buildEventItem(Event event) {
    return Column(
      children: [
        GestureDetector(
          onTap: (){
            ScheduleCtrl.to.addRecordToToday(event,DateTime.now());
            Get.back();
          },
          child: ListTile(
            leading: Icon(Icons.play_circle, color: ColorActiveRed),
            title: Text(
              event.name!,
              style: TextStyle(
                fontSize: 30.0,
                color: ColorDialogTitle,
              ),
            ),
            subtitle: Text(
              '总数：${event.totalCount}',
              style: TextStyle(
                fontSize: 20.0,
                color: ColorDialogSubtitle,
              ),
            ),
          ),
        ),
        SizedBox(height: 10.0),
      ],
    );
  }

  Widget buildEventAddItem() {
    return Column(
      children: [
        GestureDetector(
          onTap: (){
            Get.back();
            createEvent();
          },
          child: ListTile(
            leading: Icon(Icons.add, color: ColorActiveRed),
            title: Text(
              '创建项目',
              style: TextStyle(
                fontSize: 30.0,
                color: ColorDialogTitle,
              ),
            ),
          ),
        ),
        SizedBox(height: 10.0),
      ],
    );
  }
}
